<!--
* @Author: zhangjing
* @Date: 2025-04-23 16:04:25
* @Description: 开始答题=>
-->
<template>
	<div>
		<template>
			<div class="myForm">
				<div class="flex flex-align-center flex-pack-center" v-if="operateType == 'nostart'">
					<div class="form-item flex flex-align-center">
						<label>请输入知识点</label>
						<div class="my-input" style="padding: 0; background: #fff;width: 240px;">
							<a-input allow-clear v-model="klgPoint">
								<template slot="suffix" v-if="isVoiceDevice && teacherInfo && teacherInfo.machineId">
									<img
										@click="stopRecordPoint"
										v-if="hasRecordPoint"
										class="icon"
										src="/voice_active.png"
									/>
									<img @click="startRecordPoint" v-else class="icon" src="/voice.png" />
								</template>
							</a-input>
						</div>
					</div>
					<template>
						<div class="form-con flex flex-align-center">
							<div>
								<template>
									<div
										class="form-item flex flex-align-center"
										v-if="!isVoiceDevice && [0, 1].includes(formData.topicType)"
									>
										<label class="ant-form-item-required">答题范围</label>
										<div class="my-input">
											<div
												class="taglist"
												v-if="[0, 1].includes(formData.topicType) || !formData.topicType"
											>
												<div class="tag-item active">A</div>
												<div
													class="tag-item"
													@click="changeAnswerRange(item, index)"
													:class="{
														active: index <= curRangeIndex,
														lastactive: index == curRangeIndex,
													}"
													v-for="(item, index) in rangeList"
													:key="index"
												>
													{{ item }}
												</div>
											</div>
											<div class="answerRange" v-else>
												{{ formInfo.anScopeStart }}-{{ formInfo.anScopeEnd }}
											</div>
										</div>
									</div>
								</template>
							</div>
						</div>
					</template>
					<startBtn
						@startAnswer="startAnswer"
						@startQuickanswer="startQuickanswer"
						:machineData="machineData"
						:formData="formData"
					></startBtn>
				</div>
				<div v-if="operateType == 'answer'">
					<div class="extra-info" style="margin-bottom: 10px" v-if="formData.topicType == 2">
						判断题答案请输入√（正确）/×（错误）
					</div>
					<div class="extra-info" style="margin-bottom: 10px" v-if="formData.topicType == 1 && isVoiceDevice">
						选择答案后按√键提交
					</div>
					<div class="stopbox flex flex-pack-center">
						<div class="stopBtn" @click="stopAnswer">结束</div>
						<div class="resultBtn">{{ progress }}%</div>
					</div>
				</div>
				<!-- 确认答案 -->
				<div class="myForm-sureAnswer" v-if="operateType == 'sureCorrectAnswer'">
					<div class="form-con flex">
						<div class="form-item flex flex-align-center">
							<label>请选择正确答案</label>
							<div class="my-input" v-if="formData.topicType == 0">
								<a-checkable-tag
									:key="value"
									v-for="(value, indexs) in answerRangeList"
									:checked="value == totalanswer"
									@change="(checked) => changeTag(value, checked, 0)"
								>
									{{ value }}
								</a-checkable-tag>
							</div>
							<div class="my-input" v-else-if="formData.topicType == 1">
								<a-checkable-tag
									:key="value"
									v-for="(value, indexs) in answerRangeList"
									:checked="totalanswer ? totalanswer.indexOf(value) > -1 : false"
									@change="(checked) => changeTag(value, checked, 1)"
								>
									{{ value }}
								</a-checkable-tag>
							</div>
							<div class="my-input" v-else-if="formData.topicType == 2">
								<!-- <a-select v-model="totalanswer" placeholder="请选择正确答案" style="width: 100%">
									<a-select-option :value="values" v-for="(values, indexs) in answerRangeList">{{
										values
									}}</a-select-option>
								</a-select> -->
								<a-checkable-tag
									:key="value"
									v-for="(value, indexs) in ['√', '×']"
									:checked="value == totalanswer"
									@change="(checked) => changeTag(value, checked, 0)"
								>
									{{ value }}
								</a-checkable-tag>
							</div>
							<div class="my-input" v-else-if="formData.topicType == 5">
								<a-input-number v-model="totalanswer" :min="0" style="width: 100%"></a-input-number>
							</div>
						</div>
						<div class="save-btn small" @click="sureCorrectAnswer">确认</div>
					</div>
				</div>
				<template v-if="operateType == 'result'"> </template>
			</div>
		</template>
	</div>
</template>

<script>
let rangeList = ['B', 'C', 'D', 'E', 'F', 'G', 'H'];
const letterList = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];
import { topicTypeListEnum, answerTypeEnum } from '@/utils/enumeration.js';
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex';
import { getBytesLength, filterOption, debounce, padZero, convertToTimestamp, formatMsToDate } from '@/utils/base.js';
import startBtn from './startBtn.vue';
import bus from '@/utils/eventBus';
import { Snowflake } from '@/utils/base';
const snowflake = new Snowflake(BigInt(1), BigInt(1));
export default {
	props: {
		//接收器信息
		machineData: {
			type: Object,
			default: () => {},
		}, //上课数据
		formData: {
			type: Object,
			default: () => {},
		},
	},
	data() {
		return {
			operateType: 'nostart',
			rangeList,
			curRangeIndex: 2, //当前范围索引
			answerRangeList: letterList, //答案范围
			formInfo: {
				anScopeStart: 'A',
				anScopeEnd: 'D',
				testTime: undefined,
				scoreValue: null, //分值
				partScoreValue: null, //部分分
				topicType: 0,
			},
			answerlist: [],
			answerstulist: [], //发送的数量
			totalanswer: '', //正确答案
			currentKey: '',
			sendType: '', //发题类型，全答，选答，抽答
			hasQuickanswer: false, //是否有学生抢到
			klgPoint: '', //知识点
			hasRecordPoint: false, //是否
			bidObj: {},
		};
	},
	computed: {
		...mapState({
			studentList: (state) => state.websockStore.studentList,
			deviceType: (state) => state.websockStore.deviceType,
			isAnswering: (state) => state.websockStore.isAnswering,
			minProjectLogin: (state) => state.minProjectStore.minProjectLogin, //小程序是否登录
			sendTopicData: (state) => state.websockStore.sendTopicData, //小程序已发试题
			teacherInfo: (state) => state.user.teacherInfo,
			userinfo: (state) => state.user.userinfo,
			ans_id: (state) => state.websockStore.ans_id,
		}),

		progress() {
			return this.answerstulist.length > 0
				? ((this.answerlist.length / this.answerstulist.length) * 100).toFixed(2)
				: 0;
		},
		wiredAnswer() {
			return this.$store.getters.onEvent('wiredanswer');
		},
		voiceStream() {
			return this.$store.getters.onEvent('voice_stream');
		},
		klgpointChar() {
			return this.$store.getters.onKlgpointChar();
		},
		//是否是语音设备
		isVoiceDevice() {
			return ['RP554', 'RP555P'].includes(this.machineData.wareVersion);
		},
	},
	watch: {
		wiredAnswer: {
			handler(newValue, oldValue) {
				let beginClassData = this.$ls.get('beginClass');
				if (beginClassData && JSON.stringify(beginClassData) != '{}' && beginClassData.topicType != 99) {
					if (newValue && newValue != oldValue) {
						let uID = newValue.uID - 0;
						let stuInfo = this.studentList.find((item) => item.machineId - 0 == uID);
						if (stuInfo && this.sendType == 'quickanswer' && !this.hasQuickanswer) {
							//如果是抢到，且还没有学生抢到，则抢到的学生发题
							if (
								(this.isVoiceDevice && newValue.ans_str == 'G') ||
								(!this.isVoiceDevice &&
									newValue.ans_str.length > 0 &&
									newValue.ans_str.some((item) => item.type == 'hand'))
							) {
								if (this.isVoiceDevice) {
									this.studentList.forEach((item) => {
										if (item.status == 1) {
											let msg = '   ' + item.studName;
											let len = 16 - getBytesLength(msg);
											for (var i = 0; i < len; i++) {
												msg = msg + ' ';
											}
											if (item.machineId - 0 == uID) {
												msg = msg + '   抢答成功';
											} else {
												msg = msg + '   已有人抢答';
											}
											this.WEBSOCKET_SEND({
												fun: 'dtq_echo_set',
												uID: item.machineId - 0,
												msg: msg,
											});
										}
									});
								}
								this.hasQuickanswer = true;
								bus.$emit('quickanswerEvent', stuInfo);
								setTimeout(() => {
									this.startAnswer([stuInfo.studId], 'quickanswer');
								}, 1000);
							}
							return;
						}

						let answerDatetime = newValue.time ? convertToTimestamp(newValue.time) : newValue.time_stamp; //新
						let list = [];
						let tempsdTestQuestId = localStorage.getItem('tempsdTestQuestId');
						let tempsendTime = localStorage.getItem('sysTempsendTime');
						let optm = parseFloat((answerDatetime - tempsendTime) / 1000); //计算用时新
						//加数据存入缓存。
						let cardAnswerDate = this.$ls.get('cardAnswerDate') || {
							list: {},
							sdTestQuestId: '',
							sdTsTime: '',
						};
						if (cardAnswerDate.sdTestQuestId != tempsdTestQuestId) {
							cardAnswerDate = {
								sdTestQuestId: tempsdTestQuestId,
								sdTsTime: tempsendTime,
								list: {},
							};
						}
						if (this.isVoiceDevice) {
							let answer = newValue.ans_str;
							if (answer) {
								if (this.formData.topicType == 2) {
									answer = answer == 'E' ? '√' : '×';
								}
								//发送回显
								this.WEBSOCKET_SEND({
									fun: 'dtq_echo_set',
									uID,
									msg: '发送成功' + answer,
								});
								/* 先判断是否是老师设置答案 */
								if (
									this.teacherInfo &&
									this.teacherInfo.machineId &&
									this.teacherInfo.machineId - 0 == uID
								) {
									this.totalanswer = this.formData.topicType == 1 ? answer.split('') : answer;
									this.teacherHasAnswer = true;
									return;
								}

								let answerInfo = {
									sdTestQuestId: tempsdTestQuestId,
									machineId: uID,
									answer: answer,
									answerDatetime: answerDatetime,
									sdTsTime: tempsendTime,
									optm: optm < 0 ? 0 : optm,
								};

								list.push(answerInfo);
								/* 要覆盖重复提交,或者需要重新上传的 */
								let cardInfo = {
									type: this.formData.topicType,
									answer,
									id: newValue.ans_id,
									//time: answerDatetime,//旧
									time: newValue.time || '', //新
									time_stamp: newValue.time_stamp || '',
								};
								if (!stuInfo) {
									cardInfo.needUpdate = 1;
								}
								cardAnswerDate.list[padZero(newValue.uID)] = cardInfo;
								this.$ls.set('cardAnswerDate', cardAnswerDate);
							}
						} else {
							newValue.ans_str.forEach((item) => {
								//如果是空答案，丢掉
								if (item.answer) {
									let answer = item.answer;
									if (answer) {
										let answerTypeList = {
											s: 0,
											m: 1,
											j: 2,
											f: 5,
										};
										if (item.type == 'j') {
											answer = item.answer == 'true' ? '√' : '×';
										}

										let answerInfo = {
											sdTestQuestId: tempsdTestQuestId,
											machineId: uID,
											answer: answer,
											//answerDatetime: new Date(answerDatetime).getTime(),//旧
											answerDatetime: answerDatetime,
											sdTsTime: tempsendTime,
											optm: optm < 0 ? 0 : optm,
										};

										list.push(answerInfo);
										//转换答题类型
										item.type = answerTypeList[item.type];
										//转换答案
										item.answer = answer;
										item.scoreValue = 0; //即兴问答暂时分数为0

										/* 要覆盖重复提交,或者需要重新上传的 */
										let cardInfo = {
											type: item.type,
											answer,
											id: item.id,
											//time: answerDatetime,//旧
											time: newValue.time, //新
										};
										if (!stuInfo) {
											cardInfo.needUpdate = 1;
										}
										cardAnswerDate.list[padZero(newValue.uID)] = cardInfo;
										this.$ls.set('cardAnswerDate', cardAnswerDate);
									}
								}
							});
						}
						console.log('list', list, stuInfo);
						if (list.length == 0) {
							return;
						}
						this.updateAnswerProgerss(list);
						if (stuInfo) {
							let answerVals = newValue.ans_str;
							if (this.isVoiceDevice) {
								let answer = newValue.ans_str;
								if (answer) {
									if (this.formData.topicType == 2) {
										answer = answer == 'E' ? '√' : '×';
									}
								}
								let tempTopicData = this.$ls.get('tempTopicData');
								let tempInfo = tempTopicData.topicList.find(
									(item) => item.sdTestQuestId == tempsdTestQuestId
								);
								answerVals = [
									{
										id: tempInfo.bigNum + '-' + tempInfo.subNum,
										//转换答题类型
										type: this.formData.topicType,
										//转换答案
										answer,
										scoreValue: 0,
									},
								];
							}
							this.answerUpdate([
								{
									machId: newValue.dev_sn,
									cardId: padZero(newValue.uID),
									time: this.isVoiceDevice ? formatMsToDate(newValue.time_stamp) : newValue.time, //新
									optm: optm < 0 ? 0 : optm,
									answerVals: answerVals,
									sdTestQuestId: tempsdTestQuestId,
									csId: this.formData.csId,
									studId: stuInfo.studId,
									ty: answerTypeEnum[this.sendType],
								},
							]);
						}
					}
				}
			},
			immediate: true, //初始化时让handler调用一下
			deep: true, // 开启深度监听
		},
		voiceStream: {
			handler(newValue, oldValue) {
				if (newValue && JSON.stringify(newValue) != JSON.stringify(oldValue)) {
					if (this.ans_id == newValue.ans_id) {
						if (newValue.pac_num == 1) {
							this.bidObj[newValue.uID] = snowflake.nextId().toString();
						}
						if (this.bidObj[newValue.uID]) {
							let msg = {
								...newValue,
								bid: this.bidObj[newValue.uID],
								csId: this.formData.csId, //课题id
								volType: newValue.voice_type == 'speex' ? 1 : 0,
								subjCode: this.formData.subjectCode,
								fun: 'klgpoint',
							};
							this.audio_RABBITMQ_SEND(JSON.stringify(msg));
						}
					}
				}
			},
			immediate: true, //初始化时让handler调用一下
			deep: true, // 开启深度监听
		},
		klgpointChar: {
			handler(newValue, oldValue) {
				if (newValue && JSON.stringify(newValue) != JSON.stringify(oldValue)) {
					this.klgPoint = newValue.answer;
				}
			},
			immediate: true, //初始化时让handler调用一下
			deep: true, // 开启深度监听
		},
	},
	components: { startBtn },
	created() {
		this.initData();
	},
	methods: {
		...mapMutations([
			'SET_tempsdTestQuestId',
			'WEBSOCKET_SEND',
			'SET_isAnswering',
			'RABBITMQ_SEND',
			'SET_tempTestData',
			'SET_sendTopicData',
			'audio_RABBITMQ_SEND',
		]),
		async initData() {
			/* 临时题数据 */
			let tempTestData = this.$ls.get('tempTestData');
			let beginClassData = this.$ls.get('beginClass'); //上课数据
			let tempsdTestQuestId = localStorage.getItem('tempsdTestQuestId');
			if (tempTestData && JSON.stringify(tempTestData) != '{}') {
				this.formData.testQuestId = beginClassData.testQuestId;
				/* 当题目类型是单个临时题且没有发题id时 */
				if (this.formData.topicType != 100 && this.formData.topicType != 99 && !tempsdTestQuestId) {
					this.operateType = 'nostart';
					this.changeTab(this.formData.topicType);
				} else {
					this.operateType = tempTestData.operateType ? tempTestData.operateType : 'nostart'; //操作类型
					this.answerType = tempTestData.answerType; //答题类型
					this.totalanswer = tempTestData.totalanswer; //选择的正确答案
					let { anScopeStart, anScopeEnd, testTime, scoreValue, partScoreValue } = { ...tempTestData };
					this.formInfo = {
						anScopeStart,
						anScopeEnd,
						testTime,
						scoreValue, //分值
						partScoreValue, //部分分
					};
					if (this.formData.topicType == 0 || this.formData.topicType == 1) {
						this.curRangeIndex = this.rangeList.findIndex((item) => item == this.formInfo.anScopeEnd);
					}

					this.changeAnswerRange(this.formInfo.anScopeEnd, this.curRangeIndex);
				}
			} else {
				this.operateType = 'nostart';
				this.changeTab(this.formData.topicType);
			}
		},
		//切换题目类型
		changeTab(value) {
			this.formData.topicType = value;
			this.totalanswer = '';
			if (value == 0 || value == 1) {
				this.formInfo.anScopeStart = 'A';
				this.formInfo.anScopeEnd = 'D';
				this.rangeList = ['B', 'C', 'D', 'E', 'F', 'G', 'H']; //答题范围
				var startIndex1 = letterList.findIndex((item) => item == this.formInfo.anScopeStart);
				var endIndex1 = letterList.findIndex((item) => item == this.formInfo.anScopeEnd);
				this.answerRangeList = letterList.slice(startIndex1, endIndex1 + 1);
				this.totalanswer = value == 0 ? '' : [];
				this.curRangeIndex = 2;
			} else if (value == 2) {
				this.formInfo.anScopeStart = '√';
				this.formInfo.anScopeEnd = '×';
				this.rangeList = ''; //答题范围
				this.answerRangeList = ['√', '×'];
				this.totalanswer = '';
				this.curRangeIndex = null;
			} else if (value == 5) {
				this.formInfo.anScopeStart = '0';
				this.formInfo.anScopeEnd = '9999.99';
				this.rangeList = ''; //答题范围
				this.answerRangeList = '';
				this.totalanswer = null;
				this.curRangeIndex = null;
			}
		},
		//切换答案范围
		changeAnswerRange(item, index) {
			this.curRangeIndex = index;
			this.formInfo.anScopeEnd = item;
			switch (this.formData.topicType) {
				case 0:
					let startIndex = letterList.findIndex((item) => item == this.formInfo.anScopeStart);
					let endIndex = letterList.findIndex((item) => item == this.formInfo.anScopeEnd);
					this.answerRangeList = letterList.slice(startIndex, endIndex + 1);
					break;
				case 1:
					let startIndex1 = letterList.findIndex((item) => item == this.formInfo.anScopeStart);
					let endIndex1 = letterList.findIndex((item) => item == this.formInfo.anScopeEnd);
					this.answerRangeList = letterList.slice(startIndex1, endIndex1 + 1);
					break;
				case 2:
					this.answerRangeList = ['√', '×'];
					break;
				case 5:
					this.answerRangeList = [];
					break;
			}
		},
		//获取页面初始默认值
		getDefaultFormData() {
			this.operateType = 'nostart';
			this.trueAnswer = '';
			localStorage.setItem('tempsdTestQuestId', '');
			this.SET_isAnswering(0);
			//临时题数据缓存
			this.setTempData(0);
		},
		//临时题数据缓存
		setTempData(value = 0) {
			//临时题数据缓存
			/*value=1表示需要页面操作类型，0不需要  */
			console.log('表单信息' + JSON.stringify(this.formInfo));
			let newFormData = Object.assign(
				{},
				{
					operateType: value == 0 ? this.operateType : operateType ? operateType : this.operateType,
					answerType: value == 0 ? this.answerType : answerType ? answerType : this.answerType,
					totalanswer: value == 0 ? this.totalanswer : totalanswer ? totalanswer : this.totalanswer,
				},
				this.formInfo
			);
			this.$ls.set('tempTestData', newFormData);
			this.SET_tempTestData(newFormData);
		},
		//去答题
		startAnswer(selectStuList, type) {
			/* 判断移动端正在控制PC端 */
			if (this.minProjectLogin) {
				this.$message.error('移动端正在控制PC端，不能发题！');
				return;
			}
			//发题前判断该班级是否有学生。
			if (selectStuList.length == 0) {
				let beginClassData = this.$ls.get('beginClass');
				this.$message.error('（' + beginClassData.className + '）班级没有学生，请先添加学生！');
				return;
			}
			if (!this.formData.classId) {
				this.$message.error('请选择作答班级！');
				return;
			}
			if (!this.formInfo.anScopeStart || !this.formInfo.anScopeEnd) {
				this.$message.error('请选择答题范围！');
				return;
			}
			/* 校验接收器是否连接 */
			if (!this.machineData || Object.keys(this.machineData).length == 0 || !this.machineData.online) {
				this.$message.error('没有连接接收器');
				return;
			}
			this.teacherHasAnswer = false; //清空老师作答

			//这里为了如果发了导入的临时题，必须结束答题，才能发单个临时题
			let tempsdTestQuestId = localStorage.getItem('tempsdTestQuestId');
			if (tempsdTestQuestId) {
				this.$message.error('请先结束答题！');
				return;
			}
			this.answerlist = [];
			this.answerstulist = this.studentList.filter((item) => selectStuList.includes(item.studId));
			let tempquestion = this.addQuestion();
			this.sendType = type;
			this.sendTempTestPaper(tempquestion);
		},
		//临时题新增试题
		addQuestion() {
			let questions = [];
			let beginClassData = this.$ls.get('beginClass'); //上课数据
			let bigNum = 1;
			let subNum = 1;
			//临时题题号信息
			let tempTopicData = this.$ls.get('tempTopicData');
			//这里取得是缓存里面的
			if (tempTopicData && tempTopicData.topicList && tempTopicData.topicList.length > 0) {
				//比对是否是这个课题的
				if (beginClassData.csId == tempTopicData.csId) {
					let lastTopic = tempTopicData.topicList[tempTopicData.topicList.length - 1];
					let lastSubNum = lastTopic.subNum == 9999 ? 1 : lastTopic.subNum + 1;
					var lastBigNum = lastSubNum == 9999 ? lastTopic.bigNum + 1 : lastTopic.bigNum;
					bigNum = lastBigNum;
					subNum = lastSubNum;
				}
			}
			var param = {
				bigNum,
				subNum,
				topicType: this.formData.topicType,
				anScopeStart: this.formInfo.anScopeStart,
				anScopeEnd: this.formInfo.anScopeEnd,
			};
			return param;
		},
		//发送临时题
		sendTempTestPaper(tempquestion) {
			//发送题目
			let questions = [];
			let totalanScopeStart = '';
			let totalanScopeEnd = '';
			let questionType = '';
			let sendMsg = '';
			let totalbigNum = '';
			let totalsubNum = '';
			let topicitem = topicTypeListEnum.find((topicitem) => topicitem.value == this.formData.topicType);
			questionType = this.isVoiceDevice ? topicitem.videotype : topicitem.type;
			totalanScopeStart = this.formInfo.anScopeStart;
			totalanScopeEnd = this.formInfo.anScopeEnd;
			totalbigNum = tempquestion.bigNum;
			totalsubNum = tempquestion.subNum;
			sendMsg = topicitem.text + ':' + tempquestion.bigNum + '-' + tempquestion.subNum;

			//特别处理判断题，数字题答案范围
			let range = '';
			if (questionType == 'j') {
				range = '';
			} else if (questionType == 'd') {
				range = '0-9999';
			} else {
				range = totalanScopeStart + '-' + totalanScopeEnd;
			}
			const uidlist = this.answerstulist.map((item) => item.machineId - 0);
			//如果老师又答题器，需要给老师发题
			if (this.teacherInfo && this.teacherInfo.machineId) {
				uidlist.push(this.teacherInfo.machineId - 0);
			}
			console.log('this.machineData.wareVersion', this.machineData.wareVersion);
			if (this.isVoiceDevice) {
				let msg = {
					fun: 'answer_start',
					uidlist,
					type: questionType,
				};
				this.WEBSOCKET_SEND(msg);
				//发送回显
				this.WEBSOCKET_SEND({
					fun: 'dtq_echo_set',
					uidlist,
					msg: sendMsg,
				});
			} else {
				questions = [
					{
						type: questionType,
						id: totalbigNum + '-' + totalsubNum,
						range: range,
					},
				];

				let msg = {
					fun: 'answer_start',
					questions: questions,
					ans_id: totalbigNum + '-' + totalsubNum,
				};
				this.$ls.set('answer_start', {
					...msg,
				}); //保存发题信息
				this.WEBSOCKET_SEND(msg);
			}
			let { classId, csId } = this.formData;
			return this.$postAction(this.$sysManageapi.answerUrl.sendTempTestPaper, {
				classId,
				csId,
				schTopic: {
					...tempquestion,
					csId,
					klgPoint: this.klgPoint, //知识点
				},
				stuIds: this.answerstulist.map((item) => item.studId),
				teacherId: this.teacher && this.teacher.teacherId,
				type: answerTypeEnum[this.sendType], //全答，选答，抽答
				userId: this.userinfo.userId,
			}).then((res) => {
				if (res && res.code == 1) {
					this.operateType = 'answer';
					//获取临时题发题题目数据
					let topicList = [];
					let tempTopicData = this.$ls.get('tempTopicData');
					if (tempTopicData && JSON.stringify(tempTopicData) != '{}') {
						topicList = [...tempTopicData.topicList];
					}
					topicList.push({
						bigNum: tempquestion.bigNum,
						subNum: tempquestion.subNum,
						sdTestQuestId: res.data.sdTestQuestId,
					});
					//存储临时题发题题目数据
					this.$ls.set('tempTopicData', {
						csId: this.formData.csId,
						topicList,
					});
					//存储发题id
					localStorage.setItem('tempsdTestQuestId', res.data.sdTestQuestId);
					console.log('存储发题Id' + res.data.sdTestQuestId);
					//保存一次本机的发题时间。防止计算答题用时时有误差
					localStorage.setItem('sysTempsendTime', new Date().getTime());
					//设置是否正在答题
					this.SET_isAnswering(1);
					this.answerstulist.forEach((item) => {
						item.state = 0;
						item.seconds = null;
						item.answerResult = '';
					});
					//临时题数据缓存
					this.setTempData();
				}
			});
		},
		//停止作答
		stopAnswer(type) {
			/* 判断移动端正在控制PC端 */
			if (this.minProjectLogin && type != 'wxStopTemp' && type != 'autowxStopTemp') {
				this.$message.error('移动端正在控制PC端，不能操作！');
				return;
			}
			//有线
			if (this.deviceType == 'wired') {
				let msg = {
					fun: 'answer_stop',
				};
				this.WEBSOCKET_SEND(msg);
				//554发送回显
				if (this.isVoiceDevice) {
					this.studentList.forEach((item) => {
						if (item.status == 1) {
							let msg = '   ' + item.studName;
							this.WEBSOCKET_SEND({
								fun: 'dtq_echo_set',
								uID: item.machineId - 0,
								msg: msg,
							});
						}
					});
					if (this.teacherInfo && this.teacherInfo.machineId) {
						if (this.teacherInfo.status == 1) {
							let msg = '   ' + this.teacherInfo.teacherName;
							this.WEBSOCKET_SEND({
								fun: 'dtq_echo_set',
								uID: this.teacherInfo.machineId - 0,
								msg: msg,
							});
						}
					}
				}
			}
			let tempsdTestQuestId = localStorage.getItem('tempsdTestQuestId');
			return this.$postAction(this.$sysManageapi.answerUrl.stopAnswer, {
				sdQuestId: tempsdTestQuestId,
			}).then((res) => {
				if (res && res.code == 1) {
					if (
						this.totalanswer &&
						this.totalanswer.length > 0 &&
						Object.keys(this.totalanswer).length != 0 &&
						this.totalanswer != undefined
					) {
						if (this.teacherHasAnswer) {
							this.sureCorrectAnswer();
						} else {
							//设置是否正在答题
							this.SET_isAnswering(0);
						}
					} else {
						//显示输入正确答案组件
						this.operateType = 'sureCorrectAnswer';
					}
					//临时题数据缓存
					this.setTempData();
				}
			});
		},
		//确认选择正确答案
		async sureCorrectAnswer() {
			/* 判断移动端正在控制PC端 */
			if (this.minProjectLogin) {
				this.$message.error('移动端正在控制PC端，不能操作！');
				return;
			}
			if ((!this.totalanswer && this.totalanswer != 0) || this.totalanswer.length == 0) {
				this.$message.error('请选择正确答案！');
				return;
			}
			await this.updateTempTopic();
			//重新触发后端计算
			// await this.execTempPaiming();
			this.operateType = 'nostart';
			//设置是否正在答题
			this.SET_isAnswering(0);
			//临时题数据缓存
			this.setTempData();
			localStorage.setItem('tempsdTestQuestId', '');
			//查看统计页面
			this.$emit('checkMenu', { type: 'tempAnswerCount' });
		},
		//同步正确答案
		updateTempTopic() {
			let tempTopicData = this.$ls.get('tempTopicData');
			if (tempTopicData && tempTopicData.topicList.length > 0) {
				// let topicId = tempTopicData.topicList[tempTopicData.topicList.length - 1].topicId;
				let tempsdTestQuestId = localStorage.getItem('tempsdTestQuestId');
				let totalanswer =
					this.formData.topicType == 1
						? this.totalanswer.length > 0
							? this.totalanswer.sort().join('')
							: ''
						: this.totalanswer;
				let parameter = {
					answer: totalanswer,
					sdQuestId: tempsdTestQuestId,
				};
				this.$postAction(this.$sysManageapi.testquestUrl.updateTempTopic, parameter).then(() => {
					this.totalanswer = '';
				});
			}
		},
		//触发后端重新计算答题结果
		execTempPaiming() {
			let tempsdTestQuestId = localStorage.getItem('tempsdTestQuestId');
			this.$postAction(this.$sysManageapi.testquestUrl.execTempPaiming, {
				sdTestQuestId: tempsdTestQuestId,
				classId: this.formData.classId,
				isWire: this.deviceType == 'wired' ? 1 : 0,
			});
		},
		//同步答案
		answerUpdate(answerUpdate) {
			//直接推送到队列
			this.RABBITMQ_SEND(JSON.stringify(answerUpdate));
		},
		//单个题目-字母题选择
		changeTag(value, checked, type) {
			console.log(value, checked);
			//如果是单选
			if (type == 0) {
				this.totalanswer = value;
			} else {
				let selectedTags = this.totalanswer ? this.totalanswer : [];
				const nextSelectedTags = checked ? [...selectedTags, value] : selectedTags.filter((t) => t !== value);
				this.totalanswer = nextSelectedTags;
			}
		},
		//更新作答进度
		updateAnswerProgerss(answerData) {
			let seconds = '';
			let answertopicType = null; //题目类型
			answertopicType = this.formData.topicType;
			//学生名单数据
			if (answerData && answerData.length > 0) {
				console.log('更新答题记录1');
				for (var i = 0; i < answerData.length; i++) {
					for (var j = 0; j < this.answerstulist.length; j++) {
						console.log('更新答题记录2');
						//如果匹配到machineId,状态置为1，否则0，用于计算已答题人数
						if (this.answerstulist[j].machineId - 0 == answerData[i].machineId) {
							// 将时间戳转换成秒数
							this.answerstulist[j] = {
								...this.answerstulist[j],
								state: 1,
								answerResult: answerData[i].answer,
							};
							break;
						}
					}
				}
				this.answerlist = this.answerstulist.length > 0 ? this.answerstulist.filter((item) => item.state) : [];
				this.$forceUpdate();
			}
		},
		//开始抢答
		startQuickanswer() {
			//是否被抢到
			this.sendType = 'quickanswer';
			this.hasQuickanswer = false;
		},
		//开始录入知识点
		startRecordPoint() {
			this.hasRecordPoint = true;
			//给老师发送语音题
			let msg = {
				fun: 'answer_start',
				uID: this.teacherInfo.machineId - 0,
				type: 8,
			};
			this.WEBSOCKET_SEND(msg);
			this.WEBSOCKET_SEND({
				fun: 'dtq_echo_set',
				uID: this.teacherInfo.machineId - 0,
				msg: '长按语音键录知识点',
			});
		},
		//结束录入知识点
		stopRecordPoint() {
			this.hasRecordPoint = false;
			//给老师发送语音题
			let msg = {
				fun: 'answer_start',
				uID: this.teacherInfo.machineId - 0,
				type: 128,
			};
			this.WEBSOCKET_SEND(msg);
			this.WEBSOCKET_SEND({
				fun: 'dtq_echo_set',
				uID: this.teacherInfo.machineId - 0,
				msg: '   ' + this.teacherInfo.teacherName,
			});
		},
	},
};
</script>

<style scoped lang="less">
.stopbox {
	position: relative;
	.stopBtn,
	.resultBtn {
		width: 80px;
		background: #e43636;
		color: #fff;
		border-radius: 50px;
		height: 40px;
		text-align: center;
		line-height: 40px;
		font-size: 16px;
		font-weight: blod;
		cursor: pointer;
		margin-left: 10px;
	}
	.resultBtn {
		background: #ffea65;
		color: #333333;
	}
}
</style>
